package cre.tomcat.ch01;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author penglai
 * @Date 2016/12/29.
 */
public class Request {

    private InputStream inputStream;
    private String uri;
    
    public Request(InputStream inputStream) {
        this.inputStream = inputStream;    
    }

    public void parse() {
        byte[] bytes = new byte[1024];
        try {
            int i = inputStream.read(bytes);
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j <i; j++) {
                sb.append((char)bytes[j]);
            }
            System.out.println(sb.toString());
            uri = parseUri(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String parseUri(String requestString) {
        int index1, index2;
        index1 = requestString.indexOf(' ');
        if (index1 != -1) {
            index2 = requestString.indexOf(' ', index1 + 1);
            if (index2 > index1)
                return requestString.substring(index1 + 1, index2);
        }
        return "index.html";
    }

    public String getUri() {
        return uri;
    }
}
